//
//  FCCConversationListViewController.swift
//  chatUIDemo
//
//  Created by admin on 2025/7/10.
//

import UIKit
import SnapKit

class FCCConversationListViewController: UIViewController {
    
    // MARK: - 属性
    private let qfcTableView = UITableView()
    private let qfcEmptyView = UIView()
    private let qfcConversationManager: FCCConversationManager
    private var qfcConversations: [FCCConversation] = []
    
    // MARK: - 初始化
    init(qfcConversationManager: FCCConversationManager) {
        self.qfcConversationManager = qfcConversationManager
        super.init(nibName: nil, bundle: nil)
        
        // 设置会话管理器代理
        qfcConversationManager.qfcDelegate = self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        qfcSetupUI()
        qfcLoadData()
    }
    
    // MARK: - UI设置
    private func qfcSetupUI() {
        title = "Messages"
        view.backgroundColor = .white
        
        // Setup navigation bar
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .compose,
            target: self,
            action: #selector(qfcComposeNewMessage)
        )
        
        // Setup table view
        qfcTableView.delegate = self
        qfcTableView.dataSource = self
        qfcTableView.register(FCCConversationCell.self, forCellReuseIdentifier: "FCCConversationCell")
        qfcTableView.tableFooterView = UIView()
        qfcTableView.separatorStyle = .singleLine
        qfcTableView.rowHeight = 80
        
        view.addSubview(qfcTableView)
        qfcTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // Setup empty view
        let qfcEmptyLabel = UILabel()
        qfcEmptyLabel.text = "No Messages\nStart a new conversation!"
        qfcEmptyLabel.textAlignment = .center
        qfcEmptyLabel.numberOfLines = 0
        qfcEmptyLabel.textColor = .gray
        
        qfcEmptyView.addSubview(qfcEmptyLabel)
        qfcEmptyLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.8)
        }
        
        qfcEmptyView.isHidden = true
        view.addSubview(qfcEmptyView)
        qfcEmptyView.snp.makeConstraints { make in
            make.edges.equalTo(qfcTableView)
        }
    }
    
    // MARK: - 数据加载
    private func qfcLoadData() {
        // 加载模拟会话数据
        qfcConversationManager.qfcLoadMockConversations()
        qfcConversations = qfcConversationManager.qfcGetAllConversations()
        
        // 更新UI
        qfcTableView.reloadData()
        qfcUpdateEmptyViewVisibility()
    }
    
    private func qfcUpdateEmptyViewVisibility() {
        qfcEmptyView.isHidden = !qfcConversations.isEmpty
    }
    
    // MARK: - 操作
    @objc private func qfcComposeNewMessage() {
        // Create new chat (without passing conversation ID, indicating a new conversation)
        let chatVC = FCCChatViewController()
        navigationController?.pushViewController(chatVC, animated: true)
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension FCCConversationListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return qfcConversations.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FCCConversationCell", for: indexPath) as! FCCConversationCell
        
        if indexPath.row < qfcConversations.count {
            let conversation = qfcConversations[indexPath.row]
            cell.qfcConfigure(with: conversation)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.row < qfcConversations.count {
            let conversation = qfcConversations[indexPath.row]
            
            // Clear unread count
            qfcConversationManager.qfcClearUnreadCount(conversation.qfcId)
            
            // Navigate to chat view with conversation ID
            let chatVC = FCCChatViewController(qfcConversationId: conversation.qfcId)
            navigationController?.pushViewController(chatVC, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Messages"
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if indexPath.row < qfcConversations.count {
                let conversation = qfcConversations[indexPath.row]
                qfcConversationManager.qfcDeleteConversation(conversation.qfcId)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        guard indexPath.row < qfcConversations.count else { return nil }
        
        let conversation = qfcConversations[indexPath.row]
        
        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
            let deleteAction = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
                self.qfcConversationManager.qfcDeleteConversation(conversation.qfcId)
            }
            
            let markAsReadAction = UIAction(title: "Mark as Read", image: UIImage(systemName: "envelope.open")) { _ in
                self.qfcConversationManager.qfcClearUnreadCount(conversation.qfcId)
            }
            
            return UIMenu(title: "", children: [markAsReadAction, deleteAction])
        }
    }
}

// MARK: - FCCConversationManagerDelegate
extension FCCConversationListViewController: FCCConversationManagerDelegate {
    func qfcConversationManager(_ qfcManager: FCCConversationManager, didUpdateConversations qfcConversations: [FCCConversation]) {
        self.qfcConversations = qfcConversations
        qfcTableView.reloadData()
        qfcUpdateEmptyViewVisibility()
    }
    
    func qfcConversationManager(_ qfcManager: FCCConversationManager, didDeleteConversation qfcConversation: FCCConversation) {
        // 已在didUpdateConversations中处理UI更新
    }
}